#pragma once

#include <windows.h>
#include <Wininet.h>

#include "io.h"

#include "STLUtil.h"
using namespace STLUtil;

namespace FileSystemUtil
{
	static	BOOL IsRealPath( LPCTSTR pszPath ){
		return _taccess( pszPath, 00 ) ? FALSE : TRUE;
	}

	static	BOOL MakePath( const tstring sPath, BOOL bIsFileNameComprisedInPath = TRUE ){
		deque< tstring > dequePath;
		INT_PTR nCnt = STLUtil::ParsePath( sPath, dequePath, WINDOWS_PATH_DELIMITER );
		if( !nCnt )
			return FALSE;

		tstring sSubPath;
		ITERATE_CONST_EX( deque< tstring >, dequePath, i, 0, bIsFileNameComprisedInPath ? -1 : 0 ){
			sSubPath.append( ( *i ).c_str() );
			sSubPath.append( WINDOWS_PATH_DELIMITER );

			if( dequePath.begin() == i &&
				_T( ':' ) == *( sSubPath.end() - 2 ) )
				continue;

			if( !::CreateDirectory( sSubPath.c_str(), NULL ) )
				switch( ::GetLastError() )
				{
					case ERROR_ALREADY_EXISTS :
						break;
					case ERROR_PATH_NOT_FOUND :
					default :
						return FALSE;
						break;
				}
		}


		return TRUE;
	}

	static BOOL Remove( const TCHAR *pszPath ){
		if( !pszPath )
			return FALSE;

		size_t nLen = _tcslen( pszPath );
		if( !nLen )
			return FALSE;

		TCHAR szPath[ MAX_PATH ] = { 0, };
		_tcsncpy_s( szPath, MAX_PATH, pszPath, nLen );
		szPath[ _T( '\\' ) == nLen - 1 ? nLen - 2 : nLen - 1 ] = _T( '\0' );

		if( _taccess( szPath, 00 ) )
			return TRUE;
		
		SHFILEOPSTRUCT shfos = { 0 };
		shfos.hwnd   = NULL;
		shfos.wFunc  = FO_DELETE;
		shfos.pFrom  = szPath;
		shfos.fFlags = FOF_NOERRORUI | FOF_NOCONFIRMATION | FOF_SILENT;

		return SHFileOperation( &shfos );
	}

};
